package com.study.ws.config.ws.session_manager;

import jakarta.websocket.Session;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基于内存的一个会话管理系统
 *
 * @author xl-9527
 * @since 2025/3/25
 **/
@Component
public class LocalMemorySessionManagerWithWsSession implements ISessionManager<Session> {

    private static final Map<Integer, Session> SESSION_MAPPING = new ConcurrentHashMap<>();

    @Override
    public void addSession(final Session session, final Integer userId) {
        SESSION_MAPPING.put(userId, session);
    }

    @Override
    public void removeSession(final Integer userId) {
        try (Session session = SESSION_MAPPING.remove(userId)) {
            if (!Objects.isNull(session)) {
                final String message = "server: userId[" + userId + "] is offline";
                for (final Session webSocketSession : this.getAllSession()) {
                    if (webSocketSession.isOpen()) {
                        webSocketSession.getAsyncRemote().sendText(message);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Session getSession(final Integer userId) {
        return SESSION_MAPPING.get(userId);
    }

    @Override
    public Integer getUserId(final Session session) {
        for (Map.Entry<Integer, Session> entry : SESSION_MAPPING.entrySet()) {
            if (entry.getValue().equals(session)) {
                return entry.getKey();
            }
        }
        throw new RuntimeException("userId not found");
    }

    @Override
    public Collection<Session> getAllSession() {
        return SESSION_MAPPING.values();
    }
}
